package com.xfan.core.web;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import com.ibatis.sqlmap.client.SqlMapExecutor;

@SuppressWarnings("unchecked")
public class BaseDao extends SqlMapClientDaoSupport {
	protected String sqlNameSpace;
	
	public BaseDao(){
		sqlNameSpace=this.getClass().getSimpleName();
	}
	
	public BaseDao(String sqlNameSpace){
		this.sqlNameSpace=sqlNameSpace;
	}
	
	public List<Map<String, Object>> queryForList(String sql, Object map) {
		return getSqlMapClientTemplate().queryForList(sqlNameSpace +"."+ sql, map);
	}

	public Object queryForObject(String sql, Object map) {
		return getSqlMapClientTemplate().queryForObject(sqlNameSpace +"."+ sql, map);
	}
	
	public Map queryForMap(String sql, Object map,String key) {
		return getSqlMapClientTemplate().queryForMap(sqlNameSpace +"."+ sql, map,key);
	}

	public Integer queryForCount(String sql, Object map) {
		return (Integer) getSqlMapClientTemplate().queryForObject(
				sqlNameSpace +"."+ sql, map);
	}

	public int update(String sql, Object map) {
		return getSqlMapClientTemplate().update(sqlNameSpace +"."+ sql, map);
	}

	public int delete(String sql, Object map) {
		return getSqlMapClientTemplate().delete(sqlNameSpace +"."+ sql, map);
	}

	public Object insert(String sql, Object map) {
		return getSqlMapClientTemplate().insert(sqlNameSpace +"."+ sql, map);
	}

	public void batch(final String sql, final List<Object> lst) {
		this.getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor executor)
					throws SQLException {
				executor.startBatch();
				for (int i = 0, n = lst.size(); i < n; i++) {
					Object param = lst.get(i);
					executor.update(sqlNameSpace +"."+ sql, param);
				}
				executor.executeBatch();
				return null;
			}
		});
	}
}
